package com.apicloud.modulerecordscreen;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;

import com.uzmap.pkg.uzcore.UZWebView;
import com.uzmap.pkg.uzcore.uzmodule.UZModule;
import com.uzmap.pkg.uzcore.uzmodule.UZModuleContext;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Dome extends UZModule {
    private static boolean inited = false; //模块是否已经就绪

    private static final int REQUEST_CODE = 1; //ActivityResult请求code


    private UZModuleContext createContext;
    private MediaProjectionManager mediaProjectionManager;
    private RecordScreen recordScreen;

    public Dome(UZWebView webView) {
        super(webView);
    }

    private boolean checkPermission() {
        final int REQUEST_PERMISSION  = 0;
        final List<String> permissionsList = new ArrayList<>();
        if( Build.VERSION.SDK_INT < Build.VERSION_CODES.M ) return true;
        //相机权限检查
        if ((activity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
            permissionsList.add(Manifest.permission.CAMERA);
        }
        //录音权限检查
        if ((activity().checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)) {
            permissionsList.add(Manifest.permission.RECORD_AUDIO);
        }
        //手机状态权限检查
        if ((activity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
            permissionsList.add(Manifest.permission.READ_PHONE_STATE);
        }
        //文件写入权限检查
        if ((activity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        //文件读取权限检查
        if ((activity().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            permissionsList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if(permissionsList.size() == 0) return true;
        //申请权限
        activity().requestPermissions( permissionsList.toArray(new String[permissionsList.size()]) , REQUEST_PERMISSION);
        return false;
    }

    private String createFilePath(String path, boolean needMs){
        if(path.length() > 0 && path.indexOf("/")!=0) {
            path = "/"+path;
        }
        path = Environment.getExternalStorageDirectory().getPath() + path;
        if(!new File(path).exists()){
            new File(path).mkdirs();
        }
        String pattern = "yyyy-MM-dd-HH-mm-ss"+( needMs ? "-SSS" : "");
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        return path + "/" + dateFormat.format(new Date());
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode != REQUEST_CODE) return;
        MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data);
        JSONObject ret = new JSONObject();
        try {
            if(mediaProjection == null){
                ret.put("status", false).put("msg", "录屏请求被拒绝");
            }else {
                recordScreen = new RecordScreen();
                recordScreen.create(mediaProjection);
                inited = true;
                ret.put("status", true).put("msg", "创建成功");
            }
            createContext.success(ret,true);
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
    public void jsmethod_init(UZModuleContext moduleContext) throws JSONException{
        JSONObject ret = new JSONObject();
        //检查权限
        if(!checkPermission()){
            ret.put("status", false).put("msg", "缺少权限，请授权后重新初始化");
            moduleContext.success(ret,true);
            return;
        }
        //唤起录屏询问
        mediaProjectionManager = (MediaProjectionManager) activity().getSystemService(activity().MEDIA_PROJECTION_SERVICE);
        Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(captureIntent, REQUEST_CODE);
        //暂时把返回挂起，在onActivityResult中返回
        createContext = moduleContext;
    }
    public void jsmethod_start(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        //文件路径
        String path = moduleContext.optString("path","");
        int width = moduleContext.optInt("width",1080);
        int height = moduleContext.optInt("height",1920);
        int bitrate = moduleContext.optInt("bitrate",1024*1024);
        int dpi = moduleContext.optInt("dpi",1);
        int fps = moduleContext.optInt("fps",60);
        int orientation = moduleContext.optInt("orientation",0);

        String filePath = createFilePath(path, false)+".mp4";
        String errmsg = recordScreen.start(filePath, width, height, dpi, orientation, bitrate, fps);
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功").put("path", filePath);
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,false);
    }
    public void jsmethod_stop(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        String errmsg = recordScreen.stop();
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功");
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,true);
    }
    public void jsmethod_pause(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        String errmsg = recordScreen.pause();
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功");
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,true);
    }
    public void jsmethod_resume(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        String errmsg = recordScreen.resume();
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功");
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,true);
    }
    public void jsmethod_release(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        String errmsg = recordScreen.release();
        inited = false;
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功");
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,true);
    }
    public void jsmethod_imgCapture(UZModuleContext moduleContext) throws JSONException {
        JSONObject ret = new JSONObject();
        if(!inited) {
            ret.put("status", false).put("msg", "模块未初始化");
            moduleContext.success(ret,true);
            return ;
        }
        String path = moduleContext.optString("path","");
        int width = moduleContext.optInt("width",1080);
        int height = moduleContext.optInt("height",1920);
        int dpi = moduleContext.optInt("dpi",1);

        String filePath = createFilePath(path, true)+".png";
        String errmsg = recordScreen.imgCapture(filePath, width, height, dpi);
        if(errmsg == null){
            ret.put("status", true).put("msg", "操作成功").put("path", filePath);
        }else{
            ret.put("status", false).put("msg", errmsg);
        }
        moduleContext.success(ret,true);
    }

}
